package com.lib.framework.helper

/**
 * 对象 保存到文件中
 */
import android.content.Context
import android.os.Parcel
import android.os.Parcelable
import java.io.BufferedOutputStream
import java.io.FileInputStream
import java.io.FileOutputStream

/**
 * 保存 Parcelable 对象到文件中
 */
fun <T : Parcelable> saveParceObjToFile(context: Context, fileName: String, obj: T): Boolean {
    val fos: FileOutputStream
    try {
        fos = context.applicationContext.openFileOutput(fileName,
                Context.MODE_PRIVATE)
        val bos = BufferedOutputStream(fos)
        val parcel = Parcel.obtain()
        parcel.writeParcelable(obj, 0)

        bos.write(parcel.marshall())
        bos.flush()
        bos.close()
        fos.flush()
        fos.close()

        return true
    } catch (e: Exception) {
        e.printStackTrace()
    }

    return false
}

/**
 * 从配置文件获取 Parcelable 对象
 */
fun <T : Parcelable> getParceObjFromFile(context: Context, fileName: String, loader: ClassLoader): T? {
    val fis: FileInputStream
    try {
        fis = context.applicationContext.openFileInput(fileName)
        val bytes = ByteArray(fis.available())
        fis.read(bytes)
        val parcel = Parcel.obtain()
        parcel.unmarshall(bytes, 0, bytes.size)
        parcel.setDataPosition(0)

        val data: T? = parcel.readParcelable(loader)
        fis.close()

        return data
    } catch (e: Exception) {
        e.printStackTrace()
    }

    context.applicationContext.deleteFile(fileName)

    return null
}

